package com.study;

import com.influxdb.client.*;
import com.influxdb.client.domain.Query;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;

import java.time.Instant;

/**
 * @program: Default (Template) Project
 * @ClassName: ${NAME}
 * @description: influxdb操作
 * @author: csc
 * @create: 2024-03-30 14:02
 */
public class Main {

    private static char[] token = "oLpHiTew0eh9JtzdbmQLXFxKC4cuJvpfzn_NOiqR4fzhYWLmOci5c99YT5_6tILmYDTAYbDF4F7Vp1vl6jVJKw==".toCharArray();

    private static String org = "xyyl";

    /**存储桶的名称*/
    private static String bucket = "test_java";

    private static String url = "http://192.168.112.129:8086/";


    /**
     * influxdb在写入数据库数据的时候.有两个方式
     * 1. 同步写 WriteApiBlocking writeApiBlocking = influxDBClient.getWriteApiBlocking();
     *   会等待influxdb操作成功
     * 2. 异步写 WriteApi writeApi = influxDBClient.makeWriteApi();
     * @param args
     */
    public static void main(String[] args) {

        InfluxDBClient influxDBClient = InfluxDBClientFactory.create(url, token, org, bucket);
        WriteApiBlocking writeApiBlocking = influxDBClient.getWriteApiBlocking();
        WriteApi writeApi = influxDBClient.makeWriteApi();
//        writeApiBlocking.writeRecord(WritePrecision.MS,"vitalSigns,deviceNo=21090509005 heartRate=80;BloodOxygen=90 ");
//        influxDBClient.close();

        Point point = Point.measurement("vitalSigns")
                .addTag("deviceNo", "21090509005")
                .addField("heartRate", 33)
                .addField("bloodOxygen", 44)
                .time(Instant.now(), WritePrecision.MS);
//        System.out.println(point.toLineProtocol());
//        //writeApiBlocking.writePoint(point);
//        writeApiBlocking.writePoint(point);
//        influxDBClient.close();

        QueryApi queryApi = influxDBClient.getQueryApi();
        /*String flux = "from(bucket: \"test_java\")\n" +
                "  |> range(start: -1h)\n" +
                "  |> filter(fn: (r) => r[\"deviceNo\"] == \"21090509005\")\n" +
                "  |> aggregateWindow(every: 10s, fn: mean, createEmpty: false)\n" +
                "  |> yield(name: \"mean\")";*/

        String flux = "from(bucket: \"test_java\")\n" +
                "  |> range(start: -1h)\n" +
                "  |> map(fn: (r) => ({ r with rawdata: r.rawdata.string }))"+
                "  |> filter(fn: (r) => r[\"_measurement\"] == \"wave\")\n" +
                "  |> filter(fn: (r) => r[\"localtion\"] == \"device\")\n" +
                "  |> aggregateWindow(every: 10s, fn: mean, createEmpty: false)\n" +
                "  |> yield(name: \"mean\")";

        String s = queryApi.queryRaw(flux);
        System.out.println(s);

        Query query = new  Query();

    }


}